package docmanager.operation.documentos;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import docmanager.db.ConnectionPool;

import bf.DataAccess;
import bf.operation.Operation;
import bf.operation.OperationException;
import bf.utils.Util;

public class OpEliminarDocumentos1 extends Operation {

	String returnURL = "Main.jsp";
	
	@Override
	public Map execute(HttpServletRequest request) throws OperationException {


    	Map m = new HashMap();
    	String[] strIds = request.getParameterValues("id");
    	if (strIds == null || strIds.length == 0)
    	{
    		m.put("mensaje", "<h2>No se ha marcado sector</h2>");
    		return m;
    	}
        int[] ids = Util.toIntArray(strIds);

        
        Connection conn = null;
        try
        {
            conn = ConnectionPool.getConnection();
        } catch (SQLException sQLException)
        {
            sQLException.printStackTrace();
            throw new OperationException();
        }
        // Si el login ya existe, cancelar todo.
        try
        {
            conn.setAutoCommit(false);
            for (int i =0; i< ids.length; i++)
            {
                int id = ids[i];
                // Borramos primero las asociaciones.
                String query = "DELETE FROM documentos_sectores where id_documento = " + id;
                DataAccess.dmlQueryStatic(conn, query);
                // Borramos ahora al documento.
                query = "DELETE FROM documentos where id=" + id;
                DataAccess.dmlQueryStatic(conn, query);
            }
            
            conn.commit();
            conn.setAutoCommit(true);
            ConnectionPool.closeConn(conn);
        } catch (SQLException sQLException)
        {
            sQLException.printStackTrace();
            throw new OperationException();            
        }
        m.put("mensaje", "<h2>Documentos eliminados con exito</h2>");
        return m;
		
		
	}

	@Override
	public String getReturnURL() {
		return returnURL; 
	}

}
